using System.Text;
using Crossborder.Domian;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace Crossborder.Extensions
{
    public static class ServiceExtensions
    {
        public static IServiceCollection AddAuthorizationForJWT(this IServiceCollection services, IConfiguration configuration)
        {
            var tokenModel = configuration.GetSection("Jwt").Get<JwtTokenModel>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenModel.Security)),
                        ValidateIssuer = true,
                        ValidIssuer = tokenModel.Issuer,
                        ValidateAudience = true,
                        ValidAudience = tokenModel.Audience,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.FromHours(tokenModel.ClockSkew),
                    };
                    
                    options.Events = new JwtBearerEvents
                    {
                        OnChallenge = context =>
                        {
                            context.HandleResponse();
                            var res = "{\"code\":401, \"err\":\"无权限\"}";
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            context.Response.WriteAsync(res);
                            return Task.FromResult(0);
                        }
                    };
                });

            return services;
        }
    }
}